import { UiButton } from "@/shared/Uikit";
import { useGetLessonById } from "@/entities/lesson/model/useGetLessonById";
import { useEffect, useState } from "react";
import { useCompleteLesson } from "../model/useCompleteLesson";
import { useCheckMenyTests } from "../model/useCheckManyTests";

type CompleteLessonButtonProps = {
    lessonId: number,
    onSuccess?: () => void
    testIds: number[]
    onError?: (errorMessage: string) => void
}

export default function CompleteLessonButton(props: CompleteLessonButtonProps) {
    const { isSuccess, errorMessage, handleSubmit } = useCompleteLesson(props.lessonId)
    const checkManyTests = useCheckMenyTests()
    console.log(errorMessage)
    useEffect(() => {
        if (props.onSuccess && isSuccess)
            props.onSuccess()
    }, [isSuccess])

    useEffect(() => {
        if (props.onError && errorMessage)
            props.onError(errorMessage)
    }, [errorMessage, checkManyTests.errorMessage])

    useEffect(() => {
        if (checkManyTests.isSuccess) {
            if (checkManyTests.response?.passed)
                handleSubmit()
            else if (props.onError)
                props.onError('Вы неверно ответили на тесты')
        }

    }, [checkManyTests.response, checkManyTests.isSuccess])

    return (
        <>

            <UiButton variant='primary'
                onClick={() => {
                    const tests = props.testIds.map((testId) => {
                        const answers = localStorage.getItem(`testResults_${testId}`)
                        localStorage.removeItem(`testResults_${testId}`)
                        return {
                            testId,
                            answers: answers ? JSON.parse(answers) : []
                        }
                    })
                    checkManyTests.handleSubmit(tests)
                }}
            >
                Завершить
            </UiButton>
        </>
    )
}